import NProgress from 'nprogress'
import { createRouter, createWebHistory } from 'vue-router'

import { useHtmlTitle } from '@/hooks/core/useHtmlTitle'
import { useAppStore } from '@/stores/modules/app'
import LoggerUtils from '@/utils/logger'

import routes from './routes'

NProgress.configure({
  showSpinner: false
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, _from, next) => {
  NProgress.start()
  const { setHtmlTitle } = useHtmlTitle()
  setHtmlTitle(to.meta.title)

  if (to.meta.ignoreAuth) {
    return next()
  }
  if (!useAppStore().token && to.name !== 'SignIn') {
    LoggerUtils.error('未经授权，请先登录')
    return next('/sign-in')
  }
  next()
})
router.afterEach(() => {
  NProgress.done()
})
export default router
